package com.lu.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.common.constants.WmNewConstants;
import com.lu.minio.service.FileStorageService;
import com.lu.model.common.dtos.PageResponseResult;
import com.lu.model.common.dtos.ResponseResult;
import com.lu.model.common.enums.AppHttpCodeEnum;
import com.lu.model.wemedia.dto.WmMaterialDto;
import com.lu.model.wemedia.pojo.WmMaterial;
import com.lu.utils.thread.WmThreadLocalUtil;
import com.lu.wemedia.mapper.WmFileMapper;
import com.lu.wemedia.service.WmFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class WmFileServiceImpl extends ServiceImpl<WmFileMapper, WmMaterial> implements WmFileService {

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmFileMapper wmFileMapper;


    /**
     * 自媒体素材上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //上传图片
        //重定义文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //原始文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //后缀(.jpg)
        String prefix  = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        //拼接
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + prefix, multipartFile.getInputStream());
            log.info("图片{}已上传到minio", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("{}上传失败", fileId);
        }
        //保存记录到数据库
        WmMaterial wmMaterial = new WmMaterial();
        //log.info("用戶是{}", WmThreadLocalUtil.getWmUser().getId());
        wmMaterial.setUserId(WmThreadLocalUtil.getWmUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        dto.checkParam();
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //收藏的
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        wrapper.eq(WmMaterial::getUserId, 1102);
        //排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        page = page(page, wrapper);
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    /**
     * 删除图片
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Integer id) {
        if (id == null) {
            return false;
        }
        return this.removeById(id);
    }

    /**
     * 收藏图片
     * @param id
     * @return
     */
    @Override
    public int collection(Integer id) {
        if (id == null) {
            return WmNewConstants.FAIL_RESULT_CODE;
        }
        WmMaterial wmMaterial = wmFileMapper.selectOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id));
        if (wmMaterial == null) {
            return WmNewConstants.FAIL_RESULT_CODE;
        }
        wmMaterial.setIsCollection(WmNewConstants.COLLECT_MATERIAL);
        return wmFileMapper.updateById(wmMaterial);
    }


    /**
     * 取消收藏
     * @param id
     * @return
     */
    @Override
    public int noCollection(Integer id) {
        if (id == null) {
            return WmNewConstants.FAIL_RESULT_CODE;
        }
        WmMaterial wmMaterial = wmFileMapper.selectOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id));
        if (wmMaterial == null) {
            return WmNewConstants.FAIL_RESULT_CODE;
        }
        wmMaterial.setIsCollection(WmNewConstants.CANCEL_COLLECT_MATERIAL);
        return wmFileMapper.updateById(wmMaterial);
    }
}
